package domein;

import gui.*;
import java.awt.Color;
import java.awt.event.*;
import java.io.*;
import java.net.InetAddress;
import java.util.*;
import java.util.logging.*;
import javax.swing.*;

public class Control extends HashMap implements ItemListener, ActionListener {
	public static int layeredID = 100;
    private Server	server;
	private String contentBase;
	private InetAddress host;
	private int		port = 12355, backlog = 50;
	private MyFrame theFrame;
	
	public Control() {
		this.theFrame = new MyFrame(this);
		try{
			this.host = InetAddress.getLocalHost();
		} catch(IOException ex){
			System.out.println("FUK");
		}
	}

	public void doStart() {
		try {
			server = new Server(port, backlog,host,this);
			server.start();
		} catch (IOException ex) {
			Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

	public void doStop() {
		server.stop();
	}

	public void log() {

	}

	public void doBindAdress(InetAddress host) {
		this.host = host;
	}
	
	public void doPort(int portID) {
		this.port = portID;
	}

	public void doContentBase(String contentBase) {
		System.out.println("doContentBase");
		this.contentBase = contentBase;
	}
	
	public String getContentBase()
	{
		return contentBase;
	}

	@Override
	public void itemStateChanged(ItemEvent e) {
		if(e.getSource() instanceof JComboBox){
			 JComboBox box = (JComboBox)e.getSource();
			 try{
				 InetAddress inet = InetAddress.getByName((String)box.getSelectedItem());
				 doBindAdress(inet);
			 } catch(Exception ex){
				 System.out.println("No Adress By That Name");
			 }
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getActionCommand().equals("Start")){
			JButton button = (JButton)e.getSource();
			button.setText("Stop");
			button.setBackground(Color.RED);
			this.doStart();
		} else if(e.getActionCommand().equals("Stop")){
			JButton button = (JButton)e.getSource();
			button.setText("Start");
			button.setBackground(Color.GREEN);
			this.doStop();
		} else if(e.getSource() instanceof MyTextField) {
			MyTextField field = (MyTextField)e.getSource();
			if(field.getID() == 1){
				try{
					this.doPort(Integer.parseInt(field.getText()));
				} catch(NumberFormatException ex){
					JOptionPane.showMessageDialog(this.theFrame, "Port bestaat alleen uit nummers!");
				}
			} else if(field.getID() == 2){
				this.doContentBase(field.getText());
			}
		}
	}
    public void addPane(MyTextPane pane){
        MyScrollPane scrollPane = new MyScrollPane(layeredID++);
        scrollPane.setViewportView(pane);
        scrollPane.setBounds(10,50,875,300);

        this.put(scrollPane.getId(), pane);
        theFrame.addLayerToPane(scrollPane);
    }
}
